package com.css.fxfzypg.modules.similitudeAnalyse.service.impl;

import cn.hutool.core.util.IdUtil;
import com.css.fxfzypg.base.attachment.entity.AttachmentInfoEntity;
import com.css.fxfzypg.base.attachment.service.AttachmentInfoService;
import com.css.fxfzypg.modules.auxiliaryDecisionManage.paramSetting.entity.ParamSettingVO;
import com.css.fxfzypg.modules.auxiliaryDecisionManage.paramSetting.service.ParamSettingService;
import com.css.fxfzypg.modules.maps.service.SetEarthquakeMapService;
import com.css.fxfzypg.modules.similitudeAnalyse.consts.AreaConsts;
import com.css.fxfzypg.modules.similitudeAnalyse.entity.HisEarDamResult;
import com.css.fxfzypg.modules.similitudeAnalyse.entity.JcEarthquakeDamageSurvey;
import com.css.fxfzypg.modules.similitudeAnalyse.entity.RealEarthquakeEntity;
import com.css.fxfzypg.modules.similitudeAnalyse.param.QueParams;
import com.css.fxfzypg.modules.similitudeAnalyse.repository.HisEarDamResultRepository;
import com.css.fxfzypg.modules.similitudeAnalyse.resp.JCSJLszhResp;
import com.css.fxfzypg.modules.similitudeAnalyse.service.HisEarDamResultService;
import com.css.fxfzypg.modules.similitudeAnalyse.utils.ListUtil;
import com.css.fxfzypg.modules.similitudeAnalyse.vo.HisEarDamResultVO;
import com.css.fxfzypg.util.DistanceUtils;
import com.css.fxfzypg.util.PlatformObjectUtils;
import com.css.fxfzypg.util.UUIDGenerator;
import lombok.extern.slf4j.Slf4j;
import org.slw.common.helper.PropsHelper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Map;
import java.util.Properties;

@Slf4j
@Service
public class HisEarDamResultServiceImpl implements HisEarDamResultService {

    @Resource
    private SetEarthquakeMapService setEarthquakeMapService;

    @Resource
    private ParamSettingService paramSettingService;

    @Resource
    private HisEarDamResultRepository hisEarDamResultRepository;
    @Resource
    AttachmentInfoService attachmentInfoService;

    @Autowired
    private RestTemplate restTemplate;
    @Value("${basicData.url1}")
    public String basicDataUrl1;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void hisEarDamResSave(List<RealEarthquakeEntity> realEarthquakeEntities) throws ParseException {
        for (RealEarthquakeEntity item : realEarthquakeEntities) {
            List<String> provinceInfo = setEarthquakeMapService.queryProvinceByLonLat(item.getEpiLon(), item.getEpiLat());
            if (provinceInfo.size() <= 0) {
                continue;
            }
            String provinceName = provinceInfo.get(1);
            //判断是否是东部
            boolean eastFlag = ListUtil.useList(AreaConsts.EAST, provinceName);
            //判断是否是西部
            boolean westFlag = ListUtil.useList(AreaConsts.WEST, provinceName);
            //获取计算参数
            ParamSettingVO params = paramSettingService.getParamSetting();
            //假数据测试
            if ("河北邢台市沙河市".equals(item.getLocationC())) {
                provinceName="四川省";
                item.setM("6.3");
                /*item.setEpiLon("106.5");
                item.setEpiLat("29.54");*/
                item.setLocationC("四川甘孜州泸定县");
                item.setEpiLon("103.6");
                item.setEpiLat("33.2");
            }


            if (eastFlag || westFlag) {
                //是东部   判断震级是否大于4
                if(eastFlag){
                    if (AreaConsts.compare(new Double(item.getM()), AreaConsts.EAST_MAGNITUDE)) {
                        //获取实际发生地震震中位置所在区县有设定地震的或在U（默认100）公里范围内历史地震的的数据
                        JCSJLszhResp hisEarDamData = getHisEarDamData(item.getEpiLon(), item.getEpiLat(), params.getU());
                        
                        save(item,hisEarDamData.getData(),provinceName);
                    } else {
                        continue;
                    }
                }
                //是西部   判断震级是否大于5
                if(westFlag){
                    if (AreaConsts.compare(new Double(item.getM()), AreaConsts.WEST_MAGNITUD)) {
                        //获取实际发生地震震中位置所在区县有设定地震的或在O（默认50）公里范围内有设定地震的数据
                        JCSJLszhResp hisEarDamData = getHisEarDamData(item.getEpiLon(), item.getEpiLat(), params.getU());

                        save(item,hisEarDamData.getData(),provinceName);
                    } else {
                        continue;
                    }
                }

            }
        }
    }

    @Override
    public Map<String, Object> getPage(QueParams queParams, int curPage, int pageSize) {
        Map<String, Object> page = hisEarDamResultRepository.getPage(queParams,curPage, pageSize);
        return page;
    }

    @Override
    public HisEarDamResultVO fingById(String id) {
        HisEarDamResultVO vo=new HisEarDamResultVO();
        HisEarDamResult hisEarDamResult = hisEarDamResultRepository.fingById(id);
        BeanUtils.copyProperties(hisEarDamResult, vo);
        List<AttachmentInfoEntity> attachmentInfoEntities = attachmentInfoService.queryFile(hisEarDamResult.getAttachment());
        vo.setAttachments(attachmentInfoEntities);
        return vo;
    }

    private void save(RealEarthquakeEntity realEarthquakeEntity, List<JcEarthquakeDamageSurvey> list,String realProvinceName) throws ParseException {
        hisEarDamResultRepository.deleteAllData();
        for (JcEarthquakeDamageSurvey item:list) {
            Double setLon = item.getJedsLongitude();
            Double setLat = item.getJedsLatitude();
            Double realLon = new Double(realEarthquakeEntity.getEpiLon());
            Double realLat = new Double(realEarthquakeEntity.getEpiLat());
            String distance = DistanceUtils.getDistance(setLon, setLat, realLon, realLat);
            HisEarDamResult hisEarDamResult=new HisEarDamResult();

            hisEarDamResult.setId(UUIDGenerator.getUUID());
            hisEarDamResult.setRealEarthquakeLevel(new BigDecimal(realEarthquakeEntity.getM()));
            hisEarDamResult.setRealLongitude(new BigDecimal(realEarthquakeEntity.getEpiLon()));
            hisEarDamResult.setRealLatitude(new BigDecimal(realEarthquakeEntity.getEpiLat()));
            hisEarDamResult.setRealDepth(realEarthquakeEntity.getEpiDepth());
            hisEarDamResult.setRealLocation(realEarthquakeEntity.getLocationC());
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            hisEarDamResult.setRealTime(sdf.parse(realEarthquakeEntity.getOTime()));
            hisEarDamResult.setDistance(new BigDecimal(distance));
            hisEarDamResult.setJedsId(item.getJedsId());
            hisEarDamResult.setRealProvince(realProvinceName);
            List<String> provinceInfo = setEarthquakeMapService.queryProvinceByLonLat(item.getJedsLongitude().toString(), item.getJedsLatitude().toString());
            String provinceName="";
            if (!(provinceInfo.size() <= 0)) {
                provinceName = provinceInfo.get(1);
            }
            BeanUtils.copyProperties(item, hisEarDamResult);
            hisEarDamResult.setProvince(provinceName);
            hisEarDamResultRepository.save(hisEarDamResult);
        }
    }

    public JCSJLszhResp getHisEarDamData(String lon, String lat, String kilometre) {
        MultiValueMap<String, Object> param = new LinkedMultiValueMap();
        if(PlatformObjectUtils.isEmpty(lon)){
            lon="";
        }
        if(PlatformObjectUtils.isEmpty(lat)){
            lat="";
        }
        if(PlatformObjectUtils.isEmpty(kilometre)){
            kilometre="";
        }

        String url = basicDataUrl1 + "/datacenter/jcEarthquakeDamageSurvey/getEarthquakeDamageInfo?lon="+lon+"&lat="+lat+"&kilometre="+kilometre+"";
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
        headers.set("Authorization", IdUtil.simpleUUID());
        HttpEntity<MultiValueMap> r = new HttpEntity<>(param, headers);
        JCSJLszhResp response = null;
        try {
//            response = restTemplate.exchange(url, HttpMethod.GET, r, RestResponse.class).getBody();
            response= restTemplate.exchange(url, HttpMethod.GET, r, JCSJLszhResp.class).getBody();
        } catch (RestClientException e) {
            log.info("error -> url: {}", url);
            log.info("error -> param: {}", param);
            log.info("error -> exception: {}", e);
        }
        return response;
    }
}
